package cn.zpro.jeecg.mvc.service;

import java.io.File;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import cn.zpro.jeecg.mvc.util.Constant;
import cn.zpro.jeecg.mvc.util.InvokeHelper;

/**
 * MVC服务类
 * @author zhanggl
 *
 */
public class MvcService {

	public String findXmlLoadByActionNameAndActionMethod(String actionName,
			String actionMethod,HttpServletRequest req) {
		
		//从监听器中取出xml解析
		Element XML_ROOT = (Element)req.getSession().getServletContext().getAttribute(Constant.XML_ROOT);
		try {
			Element RootElt = XML_ROOT;
			List<Element> rlist = RootElt.elements();
			for (Element element : rlist) {
				String classPathName = element.attributeValue("class");
				String aname = element.attributeValue("name");
				if (actionName.contains(aname)) {// 请求的actionName
					// 反射
					InvokeHelper ink = new InvokeHelper();
					Object result = ink.invokeMethod(classPathName,
							actionMethod,req);
					List<Element> elist = element.elements();
					for (Element element2 : elist) {

						String resultName = element2.attributeValue("name")
								.toString();
						if (result.toString().equals(resultName)) {
							String url = element2.getData().toString();
							return url;
						}

					}
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}


	/**
	 * 获取xml文档根节点对象
	 * @param fileName 文件名称
	 * @return
	 */
	public Element findDocumentByFileName(String fileName){
	
		Document document;
		try {
			SAXReader reader = new SAXReader();
			String path = findXmlPath(fileName);
			document = reader.read(new File(path));
			Element RootElt = document.getRootElement();
			return RootElt;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取classPath下Xml路径
	 * 
	 * @param fileName
	 *            文件名
	 * @return
	 */
	public String findXmlPath(String fileName) {
		String path = this.getClass().getClassLoader().getResource(fileName)
				.getPath();
		path = path.substring(1, path.length());
		return path;
	}
}
